import requests
import re
import os
import time
from urllib.parse import quote

def download_baidu_images(keyword, download_count=50, download_dir="./baidu_images"):
    """
    下载百度图片搜索结果
    
    Args:
        keyword (str): 搜索关键词
        download_count (int): 想要下载的图片数量
        download_dir (str): 图片保存目录
    """
    # 创建保存目录
    if not os.path.exists(download_dir):
        os.makedirs(download_dir)
    
    # 设置请求头
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }
    
    # 编码关键词
    encoded_keyword = quote(keyword)
    
    downloaded = 0
    page_size = 60  # 每页图片数量
    pn = 0  # 页码计数器
    
    session = requests.Session()
    session.headers.update(headers)
    
    while downloaded < download_count:
        # 构建请求URL - 使用百度图片搜索接口:cite[1]:cite[5]
        url = f"https://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&word={encoded_keyword}&pn={pn}&rn=60"
        
        try:
            response = session.get(url, timeout=10)
            response.encoding = 'utf-8'
            html_content = response.text
            
            # 使用正则表达式提取图片URL:cite[1]:cite[5]
            # 匹配objURL字段（原图链接）
            pattern = r'"objURL":"(.*?)"'
            image_urls = re.findall(pattern, html_content)
            
            if not image_urls:
                print("未找到更多图片，可能已达上限")
                break
            
            print(f"第 {pn//60 + 1} 页找到 {len(image_urls)} 张图片")
            
            for img_url in image_urls:
                if downloaded >= download_count:
                    break
                    
                try:
                    # 处理转义字符
                    img_url = img_url.replace('\\/', '/')
                    
                    # 生成文件名
                    file_extension = os.path.splitext(img_url.split('/')[-1])[1]
                    if not file_extension or len(file_extension) > 5:
                        file_extension = '.jpg'
                    
                    filename = f"{keyword}_{downloaded+1:04d}{file_extension}"
                    filepath = os.path.join(download_dir, filename)
                    
                    # 下载图片
                    img_response = session.get(img_url, timeout=15)
                    
                    if img_response.status_code == 200:
                        with open(filepath, 'wb') as f:
                            f.write(img_response.content)
                        
                        downloaded += 1
                        print(f"已下载第 {downloaded} 张图片: {filename}")
                    
                    # 添加延时，避免请求过于频繁
                    time.sleep(0.5)
                    
                except Exception as e:
                    print(f"下载图片失败: {img_url}, 错误: {str(e)}")
                    continue
            
            pn += page_size
            print(f"已完成 {downloaded}/{download_count} 张图片下载")
            
        except Exception as e:
            print(f"请求失败: {str(e)}")
            break
    
    print(f"\n下载完成! 共成功下载 {downloaded} 张图片到目录: {download_dir}")

def main():
    """主函数"""
    print("=== 百度图片下载器 ===")
    
    # # 获取用户输入
    # keyword = input("请输入搜索关键词: ").strip()
    # if not keyword:
    #     print("关键词不能为空!")
    #     return
    keyword='全彩漫画'
    # try:
    #     count = int(input("请输入要下载的图片数量 (默认50): ") or "50")
    # except ValueError:
    #     count = 50
    count=100
    # download_dir = input("请输入保存目录 (默认./baidu_images): ").strip() or "./baidu_images"
    download_dir="./baidu_images"
    # 开始下载
    print(f"\n开始下载关键词 '{keyword}' 的图片...")
    download_baidu_images(keyword, count, download_dir)

if __name__ == "__main__":
    main()